package cn.eyesea.cc.frame.base.impl.resultresource;

import cn.eyesea.cc.config.GlobalConfig;
import cn.eyesea.cc.frame.base.ResourceFunction;
import cn.eyesea.cc.frame.base.ResultResource;
import cn.eyesea.cc.frame.component.NameComponent;
import cn.eyesea.cc.frame.component.ResourceComponent;
import cn.eyesea.cc.frame.enums.ResultTypeEnum;
import cn.eyesea.cc.util.ConfigUtil;
import cn.eyesea.cc.util.VelocityUtils;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;

/**
 * java类结果资源
 *
 * @author wanghuilong
 * @version 1.0
 * @date 2021/7/26 5:29 下午
 */
@Data
public class JavaClassResultResource extends ResultResource {

    /**
     * 导入信息
     */
    private Set<String> importInfos;

    /**
     * 成员变量
     */
    private List<ResultResource> memberVariables;

    @Override
    public ResultTypeEnum getResourceType() {
        return ResultTypeEnum.JAVA_CLASS;
    }

    @Override
    public void usage(ResourceFunction resourceFunction) {
        //java 类引用,导包

        //mapper 文件引用
    }

    @Override
    public void usage(ResultResource resultResource) {
        String fullName = ResourceComponent.getResourceFullName(resultResource);
        if (ResultTypeEnum.JAVA_VARIABLE.equals(resultResource.getResourceType())) {
            getMemberVariables().add(resultResource);
        }
        getImportInfos().add(fullName);
    }

    public List<ResultResource> getMemberVariables() {
        if (null == this.memberVariables) {
            this.memberVariables = new ArrayList<>();
        }
        return memberVariables;
    }

    public Set<String> getImportInfos() {
        if (null == this.importInfos) {
            this.importInfos = new HashSet<>();
        }
        return importInfos;
    }

    @Override
    public void generateCode(GlobalConfig globalConfig) {
        if (getNeedGenerateCode()) {
            Map<String, Object> param = ConfigUtil.getDefaultParam(globalConfig);
            param.put("importList", getImportInfos());
            param.put("comment", getDomainInfo().getTable() + getLogicalTypeEnum().getDesc());
            param.put("author", globalConfig.getAuthor());
            param.put("className", getName());
            List<String> memberVariableCodes = new ArrayList<>();
            List<ResultResource> memberVariables = getMemberVariables();
            if (CollectionUtils.isNotEmpty(memberVariables)) {
                for (ResultResource variableResultResource : memberVariables) {
                    variableResultResource.generateCode(globalConfig);
                    memberVariableCodes.add(variableResultResource.getGenerateCode());
                }
            }
            param.put("memberVariableCodes", memberVariableCodes);
            param.put("useData", true);
            param.put("package", getPackageInfo());
            setGenerateCode(VelocityUtils.generate("/template/javaClass.vm", param));
        }
    }

}
